/**
 * Copyright © 2015 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */
package com.eqxiu.ieditor.api.controller.mall;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eqxiu.ieditor.dto.HomeCategoryDTO;
import com.eqxiu.ieditor.dto.HotAndNewModleDTO;
import com.google.gson.Gson;
import eqxiu.mall.product.dto.CategoryDTO;
import eqxiu.mall.product.dto.HomePageCategoryDTO;
import eqxiu.mall.product.dto.RecommondCategoryDTO;
import eqxiu.mall.product.service.api.CategoryServiceApi;
import eqxiu.mall.product.service.api.HomeCategoryServiceApi;
import io.swagger.annotations.ApiImplicitParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.eqxiu.ieditor.api.mall.IMallCategoryServiceApi;
import com.eqxiu.ieditor.commons.dto.IdDTO;
import com.eqxiu.ieditor.commons.web.ResultData;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @description 商城-分类Controller
* @author  
* @modified DuYoulong 重构
* @creatTime 2019年4月3日  
* @since 1.0.0
*/
@RestController
@Api(description = "商城-分类Controller")
public class CategoryController {
	private static final Logger logger = LoggerFactory.getLogger(CategoryController.class);
	@Autowired
	private IMallCategoryServiceApi mallCategoryServiceApi;

	@Autowired
	private CategoryServiceApi categoryServiceApi;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Autowired
	private HomeCategoryServiceApi homeCategoryServiceApi;

	// h5一级分类
	@Value("${h5.back.first.id}")
	private Integer h5FirstCategory;
	// 长页一级分类
	@Value("${longpage.back.first.id}")
	private Integer longPageFirstCategory;
	//易表单一季分类
	@Value("${form.back.first.id}")
	private Integer formFirstCategory;
	//互动一级分类
	@Value("${interacth5.back.first.id}")
	private Integer gcFirstCategory;
	//请设计后端一级分类
	@Value("${design.back.first.id}")
	private Integer designFirstCategory;
	//视频后端一级分类
	@Value("${video.back.first.id}")
	private Integer videoFirstCategory;
	//最新模板
	@Value("${h5.new.modle.link}")
	private String h5NewModleLink;
	@Value("${longpage.new.modle.link}")
	private String longPageNewModleLink;
	@Value("${form.new.modle.link}")
	private String formNewModleLink;
	@Value("${gc.new.modle.link}")
	private String gcNewModleLink;
	@Value("${design.new.modle.link}")
	private String designNewModleLink;
	@Value("${video.new.modle.link}")
	private String videoNewModleLink;

	@Value("${h5.new.modle.name}")
	private String h5NewModleName;
	@Value("${longpage.new.modle.name}")
	private String longPageNewModleName;
	@Value("${form.new.modle.name}")
	private String formNewModleName;
	@Value("${gc.new.modle.name}")
	private String gcNewModleName;
	@Value("${design.new.modle.name}")
	private String designNewModleName;
	@Value("${video.new.modle.name}")
	private String videoNewModleName;


	//最热
	@Value("${h5.hot.category.id}")
	private String h5HotCategoryId;
	@Value("${longpage.hot.category.id}")
	private String longPageHotCategoryId;
	@Value("${form.hot.category.id}")
	private String formHotCategoryId;
	@Value("${gc.hot.category.id}")
	private String gcHotCategoryId;
	@Value("${design.hot.category.id}")
	private String designHotCategoryId;
	@Value("${video.hot.category.id}")
	private String videoHotCategoryId;

	@Value("${h5.hot.category.name}")
	private String h5HotCategoryName;
	@Value("${longpage.hot.category.name}")
	private String longPageHotCategoryName;
	@Value("${form.hot.category.name}")
	private String formHotCategoryName;
	@Value("${gc.hot.category.name}")
	private String gcHotCategoryName;
	@Value("${design.hot.category.name}")
	private String designHotCategoryName;
	@Value("${video.hot.category.name}")
	private String videoHotCategoryName;

	@Value("${h5.hot.category.pid}")
	private String h5HotCategoryPId;
	@Value("${longpage.hot.category.pid}")
	private String longPageHotCategoryPId;
	@Value("${form.hot.category.pid}")
	private String formHotCategoryPId;
	@Value("${gc.hot.category.pid}")
	private String gcHotCategoryPId;
	@Value("${design.hot.category.pid}")
	private String designHotCategoryPId;
	@Value("${video.hot.category.pid}")
	private String videoHotCategoryPId;
	//jibie
	@Value("${h5.hot.category.level}")
	private String h5HotCategoryLevel;
	@Value("${longpage.hot.category.level}")
	private String longPageHotCategoryLevel;
	@Value("${form.hot.category.level}")
	private String formHotCategoryLevel;
	@Value("${gc.hot.category.level}")
	private String gcHotCategoryLevel;
	@Value("${design.hot.category.level}")
	private String designHotCategoryLevel;
	@Value("${video.hot.category.level}")
	private String videoHotCategoryLevel;

	// h5前端一级分类
	@Value("${wap.h5.front.first.id}")
	private Integer h5FrontFirstCategory;
	@Value("${wap.index.front.first.id}")
	private Integer indexFrontFirstCategory;
	@Value("${wap.design.front.first.id}")
	private Integer designFrontFirstCategory;

	@ApiOperation(value = "根据分类id获取子分类")
	@GetMapping("/api/category/{cateId}")
	public ResultData categoryList(@PathVariable Integer cateId) {
		IdDTO dto = new IdDTO();
		dto.setId(cateId);
		return mallCategoryServiceApi.getListByCategoryId(dto );
	}


	@ApiOperation(value = "获取推荐分类、精选")
	@GetMapping("/api/category/recommond")
	public ResultData recommondCategoryList(Integer type) {
		String redisKey = "wapGetRecommondCategory:" + type;
		Map redismap = new HashMap();
		if (redisTemplate.opsForValue().size(redisKey) == null || redisTemplate.opsForValue().size(redisKey) == 0) {
			//type 0-wap商城首页，1-h5，2-长页，3-易表单，4-互动，5-请设计，6-视频
			Map map = new HashMap();
			List<RecommondCategoryDTO> recommondCategoryDTOList = new ArrayList<>();
			if(0==type){
				map.put("choiceCategory",null);
				//推荐枚举：8-wap商城首页，9-wap商城h5，10-wap商城长页，11-wap商城易表单，12-wap商城互动
				recommondCategoryDTOList = categoryServiceApi.findRecommendCategory(8,null);
			}else if(1==type){
				//8-wap商城首页，9-wap商城h5，10-wap商城长页，11-wap商城易表单，12-wap商城互动
				map.put("choiceCategory",h5FirstCategory);
				logger.info("分类搜索入参==={}", new Gson().toJson(h5FirstCategory));
			    recommondCategoryDTOList = categoryServiceApi.findRecommendCategory(9,h5FirstCategory);
			}else if(2==type){
				map.put("choiceCategory",longPageFirstCategory);
				//8-wap商城首页，9-wap商城h5，10-wap商城长页，11-wap商城易表单，12-wap商城互动
				recommondCategoryDTOList = categoryServiceApi.findRecommendCategory(10,longPageFirstCategory);

			}else if(3==type){
				map.put("choiceCategory",formFirstCategory);
				//8-wap商城首页，9-wap商城h5，10-wap商城长页，11-wap商城易表单，12-wap商城互动
				recommondCategoryDTOList = categoryServiceApi.findRecommendCategory(11,formFirstCategory);
			}else if(4==type){
				map.put("choiceCategory",gcFirstCategory);
				//8-wap商城首页，9-wap商城h5，10-wap商城长页，11-wap商城易表单，12-wap商城互动,13-请设计，14-视频
				recommondCategoryDTOList = categoryServiceApi.findRecommendCategory(12,gcFirstCategory);
			}else if(5==type){
				map.put("choiceCategory",designFirstCategory);
				recommondCategoryDTOList = categoryServiceApi.findRecommendCategory(13,designFirstCategory);
			}else if(6==type){
				map.put("choiceCategory",videoFirstCategory);
				recommondCategoryDTOList = categoryServiceApi.findRecommendCategory(14,videoFirstCategory);
			}
			for(RecommondCategoryDTO recommond:recommondCategoryDTOList){
				if(h5FirstCategory.equals(recommond.getTopId())){
					recommond.setType(1);
				}else if(longPageFirstCategory.equals(recommond.getTopId())){
					recommond.setType(2);
				}else if(formFirstCategory.equals(recommond.getTopId())){
					recommond.setType(3);
				}else if(gcFirstCategory.equals(recommond.getTopId())){
					recommond.setType(4);
				}else if(designFirstCategory.equals(recommond.getTopId())){
					recommond.setType(5);
				}else if(videoFirstCategory.equals(recommond.getTopId())){
					if(recommond.getDescription().contains("/")){
						String[] descrip = recommond.getDescription().split("/");
						recommond.setDescription(descrip[0]);
						if(descrip[1].trim().equals("横屏")){
							recommond.setVideoType(0);
						}else if(descrip[1].trim().equals("竖屏")){
							recommond.setVideoType(1);
						}
					}
					recommond.setType(6);
				}
			}
			map.put("recommondCategory",recommondCategoryDTOList);
			if (map != null) {
				redisTemplate.opsForValue().set(redisKey, JSONObject.toJSONString(map), 1, TimeUnit.MINUTES);
			}
			return  ResultData.result(true).setMap(map);
		}else{
			String s = redisTemplate.opsForValue().get(redisKey);
			redismap = JSON.parseObject(s);
			return ResultData.result(true).setMap(redismap);
		}
	}

	@ApiOperation(value = "获取最热、最新模板")
	@GetMapping("/api/category/hotAndNewModel")
	public ResultData hotAndNewModelList(Integer type) {
			if(null == type){
				type=1;
			}
			Map map = new LinkedHashMap();
			List<HotAndNewModleDTO> newList = new ArrayList<>();
			List<HotAndNewModleDTO> hotList = new ArrayList<>();
			//type 1-h5，2-长页，3-易表单，4-互动,5-请设计，6视频
			List<HotAndNewModleDTO> resultList = new ArrayList<>();
			if(0==type){
				List<HotAndNewModleDTO> h5HotList = dealHotAndNewMOdle(h5HotCategoryName,h5HotCategoryId,h5HotCategoryPId,h5HotCategoryLevel);
				List<HotAndNewModleDTO>	longHotList = dealHotAndNewMOdle(longPageHotCategoryName,longPageHotCategoryId,longPageHotCategoryPId,longPageHotCategoryLevel);
				List<HotAndNewModleDTO>	formHotList = dealHotAndNewMOdle(formHotCategoryName,formHotCategoryId,formHotCategoryPId,formHotCategoryLevel);
				List<HotAndNewModleDTO>	gcHotList = dealHotAndNewMOdle(gcHotCategoryName,gcHotCategoryId,gcHotCategoryPId,gcHotCategoryLevel);
				List<HotAndNewModleDTO>	designHotList  = dealHotAndNewMOdle(designHotCategoryName,designHotCategoryId,designHotCategoryPId,designHotCategoryLevel);
				List<HotAndNewModleDTO>	videoHotList = dealHotAndNewMOdle(videoHotCategoryName,videoHotCategoryId,videoHotCategoryPId,videoHotCategoryLevel);
				map.put("h5",h5HotList);
				map.put("design",designHotList);
				map.put("longPge",longHotList);
				map.put("form",formHotList);
				map.put("gc",gcHotList);
				map.put("video",videoHotList);
				return  ResultData.result(true).setMap(map);
			}else if(1==type){
				newList = dealHotAndNewMOdle(h5NewModleName,h5NewModleLink,null,null);
				hotList = dealHotAndNewMOdle(h5HotCategoryName,h5HotCategoryId,h5HotCategoryPId,h5HotCategoryLevel);
			}else if(2==type){
				newList = dealHotAndNewMOdle(longPageNewModleName,longPageNewModleLink,null,null);
				hotList = dealHotAndNewMOdle(longPageHotCategoryName,longPageHotCategoryId,longPageHotCategoryPId,longPageHotCategoryLevel);
			}else if(3==type){
				newList = dealHotAndNewMOdle(formNewModleName,formNewModleLink,null,null);
				hotList = dealHotAndNewMOdle(formHotCategoryName,formHotCategoryId,formHotCategoryPId,formHotCategoryLevel);
			}else if(4==type){
				newList = dealHotAndNewMOdle(gcNewModleName,gcNewModleLink,null,null);
				hotList = dealHotAndNewMOdle(gcHotCategoryName,gcHotCategoryId,gcHotCategoryPId,gcHotCategoryLevel);
			}else if(5==type){
				newList = dealHotAndNewMOdle(designNewModleName,designNewModleLink,null,null);
				hotList = dealHotAndNewMOdle(designHotCategoryName,designHotCategoryId,designHotCategoryPId,designHotCategoryLevel);
			}else if(6==type){
				newList = dealHotAndNewMOdle(videoNewModleName,videoNewModleLink,null,null);
				hotList = dealHotAndNewMOdle(videoHotCategoryName,videoHotCategoryId,videoHotCategoryPId,videoHotCategoryLevel);
			}
			map.put("newList",newList);
			map.put("hotList",hotList);
			return  ResultData.result(true).setMap(map);
	}


	public List<HotAndNewModleDTO> dealHotAndNewMOdle(String name,String values,String pids,String levels){

		String valueLists [] = values.split(";");
		String nameLists[] = name.split(";");
		List<HotAndNewModleDTO> resultList = new ArrayList<>();
		for(int i=0;i<valueLists.length;i++) {
			HotAndNewModleDTO hotAndNewModleDTO = new HotAndNewModleDTO();
			hotAndNewModleDTO.setName(nameLists[i]);
			hotAndNewModleDTO.setValue(valueLists[i]);
			if(!StringUtils.isEmpty(pids) && !StringUtils.isEmpty(levels)){
				String pidLists [] = pids.split(";");
				String levelsLists[] = levels.split(";");
				hotAndNewModleDTO.setPid(pidLists[i]);
				hotAndNewModleDTO.setLevel(levelsLists[i]);
			}
			resultList.add(hotAndNewModleDTO);
		}
		return resultList;
	}


	@PostMapping("/api/category/fiveCommonCategories")
	@ApiOperation(value = "获取首页左上五个推荐分类")
	@ResponseBody
	public ResultData findLeftTopFiveRecommendCategories(Integer type) {
		//type 0-首页，1-h5,2-请设计
		if(null==type){
			type = 1;
		}
		String cachedKey = "findWapLeftTopFiveCategories:"+type;
		if (redisTemplate.opsForValue().size(cachedKey) == null || redisTemplate.opsForValue().size(cachedKey) == 0) {
			try {
                Map map = new HashMap();
                map.put(h5FirstCategory, 0);
                map.put(longPageFirstCategory, 1);
                map.put(formFirstCategory, 2);
                map.put(gcFirstCategory, 3);
				map.put(designFirstCategory, 4);
				map.put(videoFirstCategory, 5);
				ArrayList<HomeCategoryDTO> result = new ArrayList<>();
				logger.info("查询与前端直接关联的分类id", h5FrontFirstCategory);
				List<HomePageCategoryDTO> list = new ArrayList<>();
				if(0==type){
					list = homeCategoryServiceApi.getCategory(indexFrontFirstCategory);
				}else if(1==type){
					list = homeCategoryServiceApi.getCategory(h5FrontFirstCategory);
				}else if(2==type){
					list = homeCategoryServiceApi.getCategory(designFrontFirstCategory);
				}
				for (HomePageCategoryDTO categoryDTO : list) {
					HomeCategoryDTO homeCategoryDTO = new HomeCategoryDTO();
					BeanUtils.copyProperties(categoryDTO, homeCategoryDTO);
					logger.info("获取详情分类信息map{}", JSONObject.toJSONString(map));
					homeCategoryDTO.setNextCategories(homeCategoryServiceApi.getCategoryDetail(categoryDTO.getId(), categoryDTO.getType(), map));
					result.add(homeCategoryDTO);
				}
				redisTemplate.opsForValue().set(cachedKey, JSONObject.toJSONString(result), 1, TimeUnit.MINUTES);
				return ResultData.result(true).setList(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			String s = redisTemplate.opsForValue().get(cachedKey);
			List<HomeCategoryDTO> result = (List<HomeCategoryDTO>) JSONArray.parseArray(s, HomeCategoryDTO.class);
			logger.info("redis获取ts={}",JSONObject.toJSONString(result) );
			return ResultData.result(true).setList(result);
		}
		return ResultData.result(true);
	}

	/**
	 * @description 按分类ID查分类列表,递归版
	 * @param id
	 * @return categoryList
	 */
	@ApiOperation(value = "根据分类id递归获取分类信息")
	@PostMapping("/api/category/getIterateCategoryListById")
	@ResponseBody
	@ApiImplicitParam(required = true, name = "id", value = "分类id", dataType = "int", paramType = "query")
	public ResultData getIterateCategoryListById(Integer id) {
		String cachedKey = "wapCategoryLists:"+ id;
		if (redisTemplate.opsForValue().size(cachedKey) == null || redisTemplate.opsForValue().size(cachedKey) == 0){
			if (id == null) {
				Map<String, Object> map = new HashMap<>();
				map.put("error", "id 不能为空");
				return ResultData.result(false).setMap(map);
			}
			List<CategoryDTO> cats = categoryServiceApi.getChildList(id);
            logger.info("获取分类是s={}", JSONObject.toJSONString(cats));
			redisTemplate.opsForValue().set(cachedKey,JSONObject.toJSONString(cats),1,TimeUnit.MINUTES);
			return ResultData.result(true).setList(cats);
		}else {
			String s = redisTemplate.opsForValue().get(cachedKey);
            logger.info("redis获取分类是s={}", JSONObject.toJSONString(s));
            List<CategoryDTO> result = (List<CategoryDTO>) JSONArray.parseArray(s, CategoryDTO.class);
            return ResultData.result(true).setList(result);
		}
	}





}
